package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class UpdateCartServlet extends HttpServlet {
    private static  final  String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
         * updateform表单的action与web.xml中要保持一致
         * cart放在session中
         * 用迭代器获取cartItems
         * 用req拿itemId
         * */

        HttpSession session = req.getSession();
        CartItem cart = (CartItem) session.getAttribute("cart");
        Account account = (Account)session.getAttribute("loginAccount");
        CartService cartService = new CartService();
        Iterator<CartItem> cartItems = cartService.getAllCartItems(account.getUsername());

        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();

            try {
                String quantityString = req.getParameter(itemId);
                int quantity = Integer.parseInt(quantityString);
                cartService.setQuantity(account.getUsername(),itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
            }
        }
        resp.sendRedirect("cartForm");
        //req.getRequestDispatcher(CART_FORM).forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
